package com.glorysoft.tonglingxjpda.ui.function.view

import android.content.Intent
import android.net.Uri
import android.os.Bundle
import android.view.View
import androidx.annotation.Nullable
import androidx.recyclerview.widget.LinearLayoutManager
import com.glorysoft.tonglingxjpda.BR
import com.glorysoft.tonglingxjpda.R
import com.glorysoft.tonglingxjpda.base.BaseActivity
import com.glorysoft.tonglingxjpda.customview.SelectorPicDialog
import com.glorysoft.tonglingxjpda.databinding.ActivityFinCheckBinding
import com.glorysoft.tonglingxjpda.entity.BatchListEntity
import com.glorysoft.tonglingxjpda.entity.DefectEntity
import com.glorysoft.tonglingxjpda.entity.ui.ToastMessageBean
import com.glorysoft.tonglingxjpda.ui.PhotoActivity
import com.glorysoft.tonglingxjpda.ui.function.viewmodel.FinCheckViewModel
import com.glorysoft.tonglingxjpda.utils.BitmapUtils
import com.glorysoft.tonglingxjpda.utils.PopWindowsUtils
import com.pda.platform.ui.ui_pdaplatform.activity_public.FreeUI_CameraActivity
import com.pda.platform.ui.ui_pdaplatform.utils_public.FreeApi_DialogUtils
import com.zhihu.matisse.Matisse
import kotlinx.android.synthetic.main.activity_fin_check.*
import kotlinx.android.synthetic.main.activity_fin_check.flDefectDesc
import kotlinx.android.synthetic.main.activity_fin_check.flDefectNum
import kotlinx.android.synthetic.main.activity_fin_check.flDefectPos
import kotlinx.android.synthetic.main.activity_fin_check.ivDefectDesc
import kotlinx.android.synthetic.main.activity_fin_check.ivDefectNum
import kotlinx.android.synthetic.main.activity_fin_check.ivDefectPic
import kotlinx.android.synthetic.main.activity_fin_check.ivDefectPos
import kotlinx.android.synthetic.main.activity_fin_check.tvDefectDesc
import kotlinx.android.synthetic.main.activity_fin_check.tvDefectNum
import kotlinx.android.synthetic.main.activity_fin_check.tvDefectPos
import java.io.File

/**
 * FileName: FinCheckActivity
 * Author: XJH
 * Date: 2022/5/10 16:28
 * Description:
 * History:
 */
class FinCheckActivity : BaseActivity<FinCheckViewModel,ActivityFinCheckBinding>(),
    View.OnClickListener, SelectorPicDialog.CameraAndAlbumListener {

    private var defectDescPop: PopWindowsUtils.GeneralPop? = null
    private var defectPosPop: PopWindowsUtils.GeneralPop? = null
    private var defectNumPop: PopWindowsUtils.GeneralPop? = null
    private var iconPath = ""
    var mDialog: SelectorPicDialog? = null

    override fun layoutId(): Int {
        return R.layout.activity_fin_check
    }

    override fun initVariableId(): Int {
        return BR.finCheckViewModel
    }

    override fun initView(savedInstanceState: Bundle?) {
        val data = intent.getSerializableExtra("DATA") as BatchListEntity.BatchInfoEntity
        setTitle("最终检查")
        viewModel.finBatchItems.add(data)
        ivDefectPic.setOnClickListener(this)
        flDefectDesc.setOnClickListener(this)
        flDefectPos.setOnClickListener(this)
        flDefectNum.setOnClickListener(this)

        viewModel.init()
        rvCurrent.layoutManager = LinearLayoutManager(this, LinearLayoutManager.HORIZONTAL, false)
        rvCurrent.setEmptyView(currentEmpty)
        rvDefect.layoutManager = LinearLayoutManager(this, LinearLayoutManager.HORIZONTAL, false)
        rvDefect.setEmptyView(defectEmpty)
        setRightListener("添加") {
            if (tvDefectDesc.text.toString().isEmpty() || tvDefectPos.text.toString()
                    .isEmpty() || tvDefectNum.text.toString().isEmpty() || iconPath.isEmpty()
            ) {
                viewModel.defUI.toastEvent.value = ToastMessageBean("请输入不良信息", false)
                return@setRightListener
            }
            showLoading()
            viewModel.addDefect(
                tvDefectDesc.text.toString(),
                tvDefectPos.text.toString(),
                tvDefectNum.text.toString(),
                iconPath
            )

        }
    }

    override fun initData() {
        mDialog = SelectorPicDialog()
        mDialog!!.setTitle("请选择照片")
        mDialog!!.setOnCameraAndAlbumListener(this)
        mDialog!!.setSelectVideo(true) //相册可以选择照片
        mDialog!!.setRecordVideo(false) //可以录制视频


        viewModel.defUI.callObserve.observe(this) {
            when (it.type) {
                0 -> {
                    when (it.item) {
                        "FAIL" -> {
                            dismissLoading()
                        }
                        "SUCCESS" -> {
                            viewModel.init()
                        }
                    }
                }
                1->{
                    showLoading()
                }
                2 -> {
                    val entity = it.item as DefectEntity.DefectInfoEntity
                    FreeApi_DialogUtils.getConfirmAndCancelDialog(this, "预览", "删除", "请选择下一步操作！",
                        {
                            val bundle = Bundle()
                            bundle.putString("PATH", entity.localPath)
                            startActivity(PhotoActivity::class.java, bundle)
                        }
                    ) {
                        viewModel.deleteDefect(entity)
                    }.show(supportFragmentManager, "SHOW_DELETE")


                }
            }
        }
    }

    override fun onClick(v: View?) {
        when (v?.id) {
            R.id.flDefectDesc -> {
                if (defectDescPop == null) {
                    defectDescPop = PopWindowsUtils.getOneChoosePop(
                        this,
                        flDefectDesc.width,
                        viewModel.defectDesc,
                        ivDefectDesc,
                        object :
                            PopWindowsUtils.PopTextAndPositionCallback {
                            override fun onSuccess(codeS: String, potion: Int) {
                                tvDefectDesc.text = codeS
                            }

                        })

                }

                if (defectDescPop!!.isShowing) {
                    defectDescPop?.dismiss()
                } else {
                    PopWindowsUtils.setArrowShow(ivDefectDesc)
                    defectDescPop?.showAsDropDown(flDefectDesc, 0, 0)
                }
            }

            R.id.flDefectPos -> {
                if (defectPosPop == null) {
                    defectPosPop = PopWindowsUtils.getOneChoosePop(
                        this,
                        flDefectPos.width,
                        viewModel.defectPos,
                        ivDefectPos,
                        object :
                            PopWindowsUtils.PopTextAndPositionCallback {
                            override fun onSuccess(codeS: String, potion: Int) {
                                tvDefectPos.text = codeS
                            }

                        })

                }

                if (defectPosPop!!.isShowing) {
                    defectPosPop?.dismiss()
                } else {
                    PopWindowsUtils.setArrowShow(ivDefectPos)
                    defectPosPop?.showAsDropDown(flDefectPos, 0, 0)
                }
            }
            R.id.flDefectNum -> {
                if (defectNumPop == null) {
                    defectNumPop = PopWindowsUtils.getOneChoosePop(
                        this,
                        flDefectNum.width,
                        viewModel.defectNum,
                        ivDefectNum,
                        object :
                            PopWindowsUtils.PopTextAndPositionCallback {
                            override fun onSuccess(codeS: String, potion: Int) {
                                tvDefectNum.text = codeS
                            }

                        })

                }

                if (defectNumPop!!.isShowing) {
                    defectNumPop?.dismiss()
                } else {
                    PopWindowsUtils.setArrowShow(ivDefectNum)
                    defectNumPop?.showAsDropDown(flDefectNum, 0, 0)
                }
            }
            R.id.ivDefectPic -> {
                mDialog!!.show(supportFragmentManager, "ICON_DIALOG")
            }
        }
    }

    override fun onActivityResult(requestCode: Int, resultCode: Int, @Nullable data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)
        //取消选择，将上次的文件置为空，重新选择更换的文件
        if (resultCode == RESULT_CANCELED) {
            return
        }
        if (resultCode == RESULT_OK || resultCode == 101) {
            when (requestCode) {
                SelectorPicDialog.REQUEST_CODE_LOCAL -> if (data != null) {
                    val pathList = Matisse.obtainPathResult(data)
                    isIconOrVideo(pathList[0], SelectorPicDialog.REQUEST_CODE_LOCAL)
                }
                SelectorPicDialog.REQUEST_CAMEAR-> {
                    val path = BitmapUtils.getPath(this, BitmapUtils.imageUri)
                    isIconOrVideo(path, SelectorPicDialog.REQUEST_VIDEO)
                }

                101 ->{
                    val path = data!!.getStringExtra("path")
                    isIconOrVideo(path, SelectorPicDialog.REQUEST_VIDEO)
                }
            }
        }

    }

    private fun isIconOrVideo(path: String, requestVideo: Int) {
        if (path.contains(".mp4")) {  //先判断地址是视频还是图片
            viewModel.defUI.toastEvent.value = ToastMessageBean("不能选择视频，请重新选择！", false)
        } else {
            //照片
            ivDefectPic.setImageURI(Uri.fromFile(File(path)))
            iconPath = path
        }
    }

    override fun OnSuccess(type: String?) {
        when (type) {
            SelectorPicDialog.TYPE_VIDEO -> FreeUI_CameraActivity.goCameraActivity(
                this,
                SelectorPicDialog.fileFolderPath
            )
            SelectorPicDialog.TYPE_ALBUM -> if (SelectorPicDialog.mSelectVideo) {
                BitmapUtils.selectPicAndTakePic(this, SelectorPicDialog.REQUEST_CODE_LOCAL, 1)
            } else {
                BitmapUtils.selectPicFromLocal(this, SelectorPicDialog.REQUEST_CODE_LOCAL, 1)
            }
            SelectorPicDialog.TYPE_CAMERA ->
                BitmapUtils.takePicture(this,SelectorPicDialog.REQUEST_CAMEAR)

//            FreeUI_CameraActivity.goCameraActivity(
//                this,
//                SelectorPicDialog.fileFolderPath
//            )
        }
    }

    override fun OnFailed(type: String?) {
        viewModel.defUI.toastEvent.value = ToastMessageBean("当前权限开启失败，请重试！", false)
    }

    override fun OnFailedNotAsking(type: String?) {
        viewModel.defUI.toastEvent.value = ToastMessageBean("当前权限开启失败，并且设置为不在询问，请去设置界面重新开启！", false)
    }
}